// @ts-nocheck
import { useState, useEffect } from 'react';
import { Modal, message, Form, Row, Col, Table, Input, Space, Card, Button, DatePicker, Divider, Upload } from 'antd'
import DistrictSelect from "@/components/Select/DistrictSelect";
import SubDistrictSelect from "@/components/Select/SubDistrictSelect";
import CommunitySelect from "@/components/Select/CommunitySelect";
import AddressSelect from "@/components/Select/AddressSelect";
import SelectPackage from "@/components/Select/SelectPackage";
import SelectDuration from "@/components/Select/SelectDuration";
import SelectEquipmentType from "@/components/Select/SelectEquipmentType";
import SelectCodeByEqType from "@/components/Select/SelectCodeByEqType";
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { createContract } from '@/services/contract'
import moment from 'moment';

const CreateContract = (props: any) => {
  const { data, onOk, onClose, visible } = props
  const dataSource = []
  dataSource.push(data)
  const clientColumns = [
    {
      title: '客户名称',
      dataIndex: 'name'
    },
    {
      title: '电话',
      dataIndex: 'telephone'
    },
    {
      title: '通信地址',
      dataIndex: 'install_address',
      width:300,
      ellipsis: true,
    },
    {
      title: '操作人',
      dataIndex: 'operator'
    }
  ]
  const [form] = Form.useForm()
  const [district, setDistrict] = useState(null)
  const [subDistrict, setSubDistrict] = useState(null)
  const [community, setCommunity] = useState(null)
  const [address, setAddress] = useState(null)
  const [back, setBack] = useState(true)
  const [duration, SetDuration] = useState(null)
  const [types, setTypes] = useState(null)
  const [files, setFiles] = useState([])
  const { TextArea } = Input;
  const onCommunitySelect = (e) => {
    const { district_id, subdistrict_id } = e
    setBack(true)
    setSubDistrict(subdistrict_id)
    setDistrict(district_id)
    form.setFieldsValue({ district: district_id, subdistrict: subdistrict_id })
  }
  const onAddressSelect = (e) => {
    const { district_id, subdistrict_id, community_id } = e
    setBack(true)
    setCommunity(community_id)
    setSubDistrict(subdistrict_id)
    setDistrict(district_id)
    form.setFieldsValue({ district: district_id, subdistrict: subdistrict_id, community: community_id })
  }
  useEffect(() => {
    if (visible) {
      setDistrict(data.district)
      setSubDistrict(data.subdistrict)
      setAddress(data.address)
      setCommunity(data.community)
      form.setFieldsValue({
        district: data.district,
        subdistrict: data.subdistrict,
        community: data.community,
        address: data.address,
        detail_address: data.detail_address,
        link_telephone: data.telephone,
        linkman: data.name
      })
    }
  }, [visible])
  const handleOk = async () => {
    const fieldsValue = await form.validateFields();
    const formData = new FormData();
    // console.log(fieldsValue.equipment)
    files.forEach((v) => {
      formData.append(`img`, v.originFileObj);
    });
    formData.append('client_id', data.client_id)
    formData.append('linkman', fieldsValue.linkman)
    formData.append('link_telephone', fieldsValue.link_telephone)
    formData.append('district', fieldsValue.district)
    formData.append('address', fieldsValue.address)
    formData.append('agreement', fieldsValue.agreement)
    formData.append('community', fieldsValue.community)
    formData.append('initial_money', fieldsValue.initial_money)
    formData.append('detail_address', fieldsValue.detail_address)
    formData.append('equipment', JSON.stringify(fieldsValue.equipment))
    formData.append('memo', fieldsValue.memo)
    formData.append('service_package', fieldsValue.service_package)
    formData.append('subdistrict', fieldsValue.subdistrict)
    formData.append('installer', fieldsValue.installer)
    formData.append('start_date', moment(fieldsValue.start_date).format('YYYY-MM-DD'))
    createContract(formData).then(res => {
      if (res.status === 200) {
        onOk()
        message.success(res.message).then()
      } else {
        message.error(res.message).then()
      }
    })
  }
  // @ts-ignore
  // @ts-ignore
  return (
    <Modal
      destroyOnClose
      title={'业务办理'}
      keyboard={false}
      maskClosable={false}
      onCancel={onClose}
      visible={visible}
      width={'60vw'}
      onOk={handleOk}
    >
      <Space direction="vertical" size="middle" style={{ display: 'flex' }}>
        <Card bordered={false}>
          <Table columns={clientColumns} dataSource={dataSource} size="small" pagination={false} />
        </Card>
        <Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 14 }} autoComplete="off">
          <Row>
            <Col span={12}>
              <Form.Item label="客户名称" name="linkman" rules={[{ required: true, message: '请输入客户名称' }]}>
                <Input placeholder={'请输入客户名称'} allowClear />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="手机号" name="link_telephone" >
                <Input maxLength={11} placeholder={'请输入手机号'} allowClear />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="所属区域" name="district" rules={[{ required: true, message: '请选择所属区域' }]}>
                <DistrictSelect onChange={(e) => {
                  setBack(false);
                  setDistrict(e)
                }} defaultValue={district} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="所属街道" name="subdistrict" rules={[{ required: true, message: '请选择所属街道' }]}>
                <SubDistrictSelect onChange={(e) => {
                  setBack(false);
                  setSubDistrict(e)
                }} district={district} defaultValue={subDistrict} back={back} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="所属园区" name="community" rules={[{ required: true, message: '请选择所属园区' }]}>
                <CommunitySelect onSelect={(e) => onCommunitySelect(e)} onChange={(e) => {
                  setCommunity(e)
                }}
                  subDistrict={subDistrict} district={district} defaultValue={community} back={back} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="蓝牌地址" name="address" rules={[{ required: true, message: '请选择蓝牌地址' }]}>
                <AddressSelect onSelect={(e) => onAddressSelect(e)} onChange={(e) => setAddress(e)}
                  community={community}
                  district={district}
                  subDistrict={subDistrict} back={back}
                  defaultValue={address} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="详细地址" name="detail_address" rules={[{ required: true, message: '请输入详细地址' }]}>
                <TextArea autoSize allowClear placeholder={'请输入详细地址'} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="计费周期">
                <SelectDuration onChange={e => SetDuration(e)} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="计费套餐" name="service_package" rules={[{ required: true, message: '请选择计费套餐' }]}>
                <SelectPackage duration={duration} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="初装费用" name="initial_money" rules={[{ required: true, message: '请输入初装费用' }]}>
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="开始时间" name="start_date" initialValue={moment()}>
                <DatePicker defaultValue={moment()} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="协议单号" name={'agreement'} rules={[{ required: true, message: '请输入详细地址' }]}>
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="装维人员" name='installer' rules={[{ required: true, message: '请输入装维人员' }]}>
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="备注" name={'memo'}>
                <TextArea autoSize />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label={"协议上传"} name="agreement_img" >
                <Upload
                  listType="picture-card"
                  accept=".jpg, .jpeg, .png"
                  onChange={({ fileList }) => setFiles(fileList)}
                >
                  {files.length >= 1 ? null : <div>
                    <PlusOutlined />
                    <div style={{ marginTop: 8 }}>上传协议单</div>
                  </div>}
                </Upload>
              </Form.Item>
            </Col>
          </Row>
          <Divider />
          <Row>
            <Col span={24}>
              <Form.List name='equipment'>
                {(fields, { add, remove }) => {
                  return (
                    <div style={{ marginLeft: '64px' }}>
                      {fields.map(field => (
                        <Space key={field.key} style={{ display: 'flex', marginBottom: 4 }} align='start'>
                          <Row>
                            <Col span={6}>
                              <Form.Item
                                {...field}
                                name={[field.name, 'equipment_type']}
                                label={'设备类型'}
                                style={{ width: '300px' }}
                                rules={[{ required: true, message: '请选择设备类型' }]}
                              >
                                <SelectEquipmentType onChange={e => setTypes(e)} />
                              </Form.Item>
                            </Col>
                            <Col span={8}>
                              <Form.Item
                                {...field}
                                name={[field.name, 'code']}
                                label={'设备编码'}
                                style={{ width: '300px', marginLeft: '40px' }}
                                rules={[{ required: true, message: '请选择设备编码' }]}
                              >
                                <SelectCodeByEqType types={types} />
                              </Form.Item>
                            </Col>
                            <Col span={4}>
                              <Form.Item {...field} name={[field.name, 'money']} label={'金额'}
                                style={{ width: '300px' }} rules={[{ required: true, message: '请输入金额' }]}>

                                <Input />
                              </Form.Item>
                            </Col>
                            <Col span={6}>
                              <MinusCircleOutlined
                                className='dynamic-delete-button'
                                style={{ lineHeight: '32px', marginLeft: '80px' }}
                                onClick={() => {
                                  remove(field.name);
                                }}
                              />
                            </Col>
                          </Row>
                        </Space>
                      ))}
                      <Col span={24}>
                        <Form.Item>
                          <Button
                            type='dashed'
                            onClick={() => {
                              add();
                            }}
                            block
                          >
                            <PlusOutlined /> 增加设备
                          </Button>
                        </Form.Item>
                      </Col>
                    </div>
                  );
                }}
              </Form.List>
            </Col>
          </Row>
          <Divider />
        </Form>
      </Space>


    </Modal>
  );
};

export default CreateContract;
